<template>
  <div>
    <!-- 下拉刷新 -->
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      :disabled="finished"
    >
      <!-- 上拉加载更多 -->
      <!-- :immediate-check="false" 防止一进入组件就触发load事件 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="木有更多数据了~亲"
        @load="onload"
        :immediate-check="false"
      >
        <!-- 循环生成文章的Item项组件 -->
        <ArtItem
          v-for="item in artList"
          :key="item.art_id"
          :article="item"
          @remove-article="removeArticle"
        ></ArtItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArtListAPI } from '@/api/homeAPI.js'
import ArtItem from '@/components/ArtItem/ArtItem.vue'
export default {
  name: 'ArtList',
  props: {
    channelId: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      // 文章的列表
      artList: [],
      // 调用 API接口要传递的时间戳
      timestamp: Date.now(),
      // 是否正在加载数据
      loading: true,
      // 所有数据是否加载完毕
      finished: false,
      // 是否正在请求下拉刷新的数据
      isLoading: false
    }
  },
  components: {
    ArtItem
  },
  created () {
    this.initArtList()
  },
  methods: {
    onload () {
      this.initArtList()
    },
    onRefresh () {
      this.initArtList(true)
    },
    // 初始化文章的列表数据
    // isPullDow 表示用户执行下拉刷新的动作
    async initArtList (isPullDow) {
      const { data: res } = await getArtListAPI(this.channelId, this.timestamp)
      if (res.message === 'OK') {
        // 数据请求成功之后,要做两件事情:
        // 1.为timestamp 赋值
        this.timestamp = res.data.pre_timestamp

        // 2.为artList 赋值,拼接新旧数据
        if (isPullDow) {
          // 下拉刷新 新数据,旧数据
          this.artList = [...res.data.results, ...this.artList]
        } else {
          // 上拉加载更多 就数据,新数据
          this.artList = [...this.artList, ...res.data.results]
        }
        this.loading = false
        this.isLoading = false
        // 判断所有数据是否加载完毕
        if (res.data.pre_timestamp === null) {
          this.finished = true
        }
      }
    },
    removeArticle (id) {
      this.artList = this.artList.filter(item => item.art_id !== id)
      if (this.artList.length < 10) {
        this.initArtList()
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
